package com.tf_cut.admin.backend.controller;

import com.alibaba.fastjson.JSONObject;
import com.tf_cut.admin.backend.api.BackEndApi;
import com.tf_cut.admin.backend.vo.RegisterVo;
import com.tf_cut.admin.common.pojo.Result;
import com.tf_cut.admin.seller.vo.SellerProjectVo;
import com.tf_cut.admin.sys.sysauthority.service.SysAuthorityService;
import com.tf_cut.admin.sys.sysauthority.vo.SysAuthorityVo;
import com.tf_cut.admin.sys.sysuser.service.SysUserService;
import com.tf_cut.admin.sys.sysuser.vo.SysUserVo;
import com.tf_cut.admin.sys.sysuserauthority.service.SysUserAuthorityService;
import com.tf_cut.admin.sys.sysuserauthority.vo.SysUserAuthorityVo;
import com.tf_cut.admin.user.service.UserService;
import com.tf_cut.admin.util.CacheUtil;
import com.tf_cut.admin.util.CalendarUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;


@RestController
@RequestMapping("/backend/seller/mobile")
@Slf4j
public class SellerMobileController {

    @Autowired
    private BackEndApi backEndApi;

    @Autowired
    private UserService userService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUserAuthorityService sysUserAuthorityService;

    @Autowired
    private SysAuthorityService sysAuthorityService;

    @Autowired
    private AgentMobileController agentMobileController;


    @PostMapping("/register")
    public  Result register(@RequestBody RegisterVo registerVo){
        try {
            //判断手机号重复
            Result<SysUserVo> byLoginName = this.sysUserService.findByLoginName(registerVo.getLoginName());
            if(byLoginName.getData()==null||!byLoginName.isFlag()){
                return  Result.of(registerVo,false,"该手机号已注册");
            }
            String code = CacheUtil.get(registerVo.getLoginName());
            CacheUtil.delete(registerVo.getLoginName());

            log.debug("code:"+code);
            log.debug("VerifyCode:"+registerVo.getVerifyCode());
            // 调试时注释，正式用要开启
            if(StringUtils.isBlank(registerVo.getVerifyCode()) || StringUtils.isBlank(code) ||StringUtils.compareIgnoreCase(registerVo.getVerifyCode(),code) != 0){
                return Result.of(null, false, "验证码错误");
            }

            //新增系统用户
            SysUserVo sysUserVo = SysUserVo.builder()
                    .createTime(new Date())
                    .updateTime(new Date())
                    .lastChangePwdTime(new Date())
                    .loginName(registerVo.getLoginName())
                    .userName(registerVo.getCompanyName())
                    .password(registerVo.getPassword())
                    .valid("Y")
                    .limitMultiLogin("Y")
                    .build();
            Result<SysUserVo> save = this.sysUserService.save(sysUserVo);
            //增加用户权限
            List<SysAuthorityVo> seller_user = this.sysAuthorityService.list(SysAuthorityVo.builder().authorityName("SELLER_USER").build()).getData();
            //如果获取商户权限菜单失败
            if(seller_user==null || seller_user.isEmpty()){
                return   Result.of(registerVo,false,"系统数据有误");
            }
            //给该商户授权使用菜单
            SysUserAuthorityVo build = SysUserAuthorityVo.builder().userId(save.getData().getUserId())
                    .authorityId(seller_user.get(0).getAuthorityId()).createTime(new Date()).build();
            this.sysUserAuthorityService.save(build);

            //增加商户信息及账户信息
            JSONObject object=new JSONObject();
            object.put("sellerCompanyName",registerVo.getCompanyName());
            object.put("loginId",save.getData().getUserId());
            object.put("loginName",registerVo.getLoginName());
            object.put("isAuthentication","N");//没有认证
            object.put("sellerState", "Y");
            String result = this.backEndApi.insertmobileSellerAndAccount(object.toJSONString());
            JSONObject jsonObject = JSONObject.parseObject(result, JSONObject.class);
            if(!jsonObject.getBoolean("flag")){
                return Result.of(null, false, "创建商户失败");
            }
            //增加登录信息
            JSONObject login=new JSONObject();
            login.put("isverifycode", false);
            login.put("username",registerVo.getLoginName());
            login.put("password", registerVo.getPassword());
            Object login1 = this.agentMobileController.login(login.toJSONString());
            save.setMsg(login1.toString());
            return save;
        } catch (Exception e) {
            e.printStackTrace();
            return   Result.of(registerVo,false,"不能重复注册商户");
        }
    }

    /*
    //商户签约代理商
    @PostMapping("/signContact")
    public  Result signContact(@RequestBody SellerRefAgentVo sraVo){
        //根据电话号码获取代理商id
        String agentId = "";
        String agentPhone = sraVo.getAgentPhone();
        if(!agentPhone.equals("")) {
            JSONObject objAgent = new JSONObject();
            objAgent.put("agentPhone", agentPhone);
            String result = this.backEndApi.findListAgent(objAgent.toJSONString());
            JSONObject jsonAgent = JSONObject.parseObject(result, JSONObject.class);
            // 取出得到json数组
            String content = jsonAgent.getString("rows");
            // 将json数组存到list中
            List<JSONObject> jsonObjectList = JSONObject.parseArray(content, JSONObject.class);
            if (jsonObjectList==null) {
                return Result.of(null, false, "没有找到代理商信息");
            }
            // 遍历json数组并取出想要的数据
            for (JSONObject jsonObj : jsonObjectList) {
                if (jsonObj.getString("agentPhone").equals(agentPhone)) {
                    agentId = jsonObj.getString("agentId");
                    break;
                }
            }
            if (agentId.equals("")) {
                return Result.of(null, false, "没有找到代理商信息");
            }
        }

        //获取代理商签约点数
        BigDecimal servePoint = registerVo.getServePoint();

        if(!agentPhone.equals("") ) {

            //添加到 商户-代理商 关联表
            SellerRefAgentVo avo = SellerRefAgentVo.builder()
                    //.relationId("")
                    .agentId(agentId)
                    .sellerId(sellerId)
                    .serverAmountPoint(servePoint)
                    .refState("Y")
                    .build();
            String json = JSON.toJSONString(avo);
            json = backEndApi.saveSellerRefAgent(json);
            return JSON.parseObject(json, Result.class);
//                JSONObject objAgentRefSeller = new JSONObject();
//                objAgentRefSeller.put("relationId", "123456789");
//                objAgentRefSeller.put("agentId", agentId);
//                objAgentRefSeller.put("sellerId", sellerId);
//                objAgentRefSeller.put("serverAmountPoint", servePoint);
//                objAgentRefSeller.put("refState", "Y");
//                result = this.backEndApi.saveSellerRefAgent(objAgentRefSeller.toJSONString());
//                JSONObject jsonObj = JSONObject.parseObject(result, JSONObject.class);
//                if(!jsonObj.getBoolean("flag")){
//                    return Result.of(jsonObj, false, "创建商户签约代理商失败");
//                }
        }
        return   Result.of(sraVo,false,"签约信息：");
    }
    */


    @GetMapping(value = "/getSellerByloginId")
    public String get(@RequestParam("loginId")  String loginId){
        return backEndApi.sellermobileget(loginId);
    }

    @PostMapping(value = "/sellerAuth")
    public String updateInfo(@RequestBody String svo){
        return backEndApi.updatemobileInfo(svo);
    }

    @PostMapping(value = "/insertProject")
    public String insertproject(@RequestParam("token") String token,@RequestBody String svo){
        //获取用户流水号
        String userId=CacheUtil.get(token);
        Result<SysUserVo> result=sysUserService.get(userId);
        JSONObject jsonObject = JSONObject.parseObject(svo);
        jsonObject.put("merchantNumber",result.getData().getMerchantNumber());
        jsonObject.put("platform",result.getData().getPlatform());
        log.debug(jsonObject.toJSONString());
        return backEndApi.insertproject(jsonObject.toJSONString());
    }

    @PostMapping(value = "/insertProjectPerson")
    public String insertProjectPerson(@RequestBody String svo){
        return backEndApi.insertprojectperson(svo);
    }

    @GetMapping(value = "/fingPageProject")
    public String fingPageProject(
                              @RequestParam(value = "checkedType",required = false) String checkedType,
                              @RequestParam(value = "startDate",required = false) String startDate,
                              @RequestParam(value = "endDate",required = false) String endDate,

                              @RequestParam(value = "projectName",required = false)String projectName,
                              @RequestParam(value = "havePersonInfo",required = false) String havePersonInfo,
                               @RequestParam(value = "personInfoId",required = false) String personInfoId,
                              @RequestParam(value = "pageNum",required = false) Integer pageNum,
                              @RequestParam(value = "pageSize",required = false) Integer pageSize){
        if("本月".equals(checkedType)){
            startDate= CalendarUtil.getCurrentMonthStartTime();
            endDate=CalendarUtil.getCurrentMonthEndTime();
        }else if("本季度".equals(checkedType)){
            startDate=CalendarUtil.getCurrentQuarterStartTime();
            endDate=CalendarUtil.getCurrentQuarterEndTime();
        }else if("本年".equals(checkedType)){
            startDate=CalendarUtil.getCurrentYearStartTime();
            endDate=CalendarUtil.getCurrentYearEndTime();
        }
        String reslt= backEndApi.fingPageProject(projectName,startDate,endDate,havePersonInfo,personInfoId,pageNum,pageSize);
        return reslt;
    }
    
    @GetMapping(value = "/projectdetail")
    public Result<List<SellerProjectVo>> fingProject(@RequestParam("sellerName") String sellerName,
                              @RequestParam("checkedType") String checkedType,
                              @RequestParam("startDate") String startDate,
                              @RequestParam("endDate") String endDate,
                              @RequestParam("personName") String personName,
                              @RequestParam("projectName")String projectName){
        if("本月".equals(checkedType)){
            startDate= CalendarUtil.getCurrentMonthStartTime();
            endDate=CalendarUtil.getCurrentMonthEndTime();
        }else if("本季度".equals(checkedType)){
            startDate=CalendarUtil.getCurrentQuarterStartTime();
            endDate=CalendarUtil.getCurrentQuarterEndTime();
        }else if("本年".equals(checkedType)){
            startDate=CalendarUtil.getCurrentYearStartTime();
            endDate=CalendarUtil.getCurrentYearEndTime();
        }
        List<SellerProjectVo>list= backEndApi.fingProject(personName,sellerName,projectName,startDate,endDate);
        return Result.of(list);
    }

    @GetMapping("/project/view")
    public Result<SellerProjectVo> projectview(
            @RequestParam(value = "projectId",required = false) String projectId,
            @RequestParam(value = "personInfoId",required = false) String personInfoId){
        return backEndApi.projectview(projectId,personInfoId);
    }



    //新增根据供应商查询
    @GetMapping("/project/findBySellerId")
    public Result<List<SellerProjectVo>> findBySellerId(
            @RequestParam(value = "projectName",required = false)String projectName,
            @RequestParam("checkedType") String checkedType,
            @RequestParam(value = "startDate",required = false) String startDate,
            @RequestParam(value = "endDate",required = false) String endDate,
            @RequestParam(value = "sellerId",required = false) String sellerId){

        if("本月".equals(checkedType)){
            startDate= CalendarUtil.getCurrentMonthStartTime();
            endDate=CalendarUtil.getCurrentMonthEndTime();
        }else if("本季度".equals(checkedType)){
            startDate=CalendarUtil.getCurrentQuarterStartTime();
            endDate=CalendarUtil.getCurrentQuarterEndTime();
        }else if("本年".equals(checkedType)){
            startDate=CalendarUtil.getCurrentYearStartTime();
            endDate=CalendarUtil.getCurrentYearEndTime();
        }
        List<SellerProjectVo> bySellerId = this.backEndApi.findBySellerId(projectName, startDate, endDate, sellerId);
        return Result.of(bySellerId);
    }

    @GetMapping("/project/findProjectPersonInfoByProjectId")
    public String findProjectPersonInfoByProjectId(
            @RequestParam(value = "projectId",required = false) String projectId){
        return this.backEndApi.findProjectPersonInfoByProjectId(projectId);
    }


    @GetMapping(value = "/billtypelist")
    public String billTypeList(){
        return backEndApi.billTypeList();

    }


    @PostMapping(value = "/billinsert")
    public String insertBill(@RequestBody String svo){
        return backEndApi.insertBill(svo);
    }

}
